package com.jsbs.iam.user.controller;

import com.github.pagehelper.PageInfo;
import com.jsbs.iam.common.core.dto.Result;
import com.jsbs.iam.common.core.utils.Json;
import com.jsbs.iam.user.constant.Constants;
import com.jsbs.iam.user.dto.*;
import com.jsbs.iam.user.entity.IamOrganizationTypeBase;
import com.jsbs.iam.user.service.OrgTypeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * @BelongsProject: iam
 * @BelongsPackage: com.jsbs.iam.user.controller
 * @Author: WangJiYuan
 * @Description: TODO
 * @Version: 2022-12-02  17:34
 */
@Slf4j
@RestController
@RequestMapping("/iam/user/orgType")
public class OrgTypeController extends BaseController{

    private static final Logger LOGGER = LoggerFactory.getLogger(OrgTypeController.class);

    @Autowired
    private OrgTypeService orgTypeService;

    private static final String ADMIN_USER = "admin";

    /**
     * 查询组织类型数据
     * @return
     */
    @PostMapping("/getOrgTypeData")
    public Result getOrgTypeData(HttpServletRequest httpServletRequest) {
        log.info("Route=>OrgTypeController method=>getOrgTypeData 查询组织类型数据");
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String adminRoleCode = httpServletRequest.getHeader(Constants.ADMIN_ROLE_CODE);
            companyCode = "000001";
            userCode = "admin";
            adminRoleCode = "JS0030";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>OrgTypeController method=>getOrgTypeData 查询组织类型数据，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            if (StringUtils.isEmpty(userCode)) {
                log.warn("Route=>OrgTypeController method=>getOrgTypeData 查询组织类型数据，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            if (!ADMIN_USER.equals(userCode) && StringUtils.isEmpty(adminRoleCode)) {
                log.warn("Route=>OrgTypeController method=>getOrgTypeData 查询组织类型数据，当前登录人角色信息异常");
                return Result.failWithMsg("登录人角色信息异常");
            }
            List<IamOrganizationTypeBase> info = orgTypeService.getOrgTypeData(companyCode, userCode, adminRoleCode);
            return new Result(Result.SUCCESS, "查询组织类型成功", info);
        } catch (Exception e) {
            LOGGER.error("Route==>OrgTypeController method=>getOrgTypeData 查询组织类型数据异常，入参：{}，异常：{}","", e);
            return handleException(e);
        }
    }

    /**
     * 新增组织类型
     * @param orgTypeAddDto
     * @return
     */
    @PostMapping(value = "/addOrgType")
    //@LogDb
    public Result addOrgType(HttpServletRequest httpServletRequest, @RequestBody OrgTypeAddDto orgTypeAddDto) {
        log.info("Route=>OrgTypeController method=>addOrgType 新增组织类型：{}", Json.toJsonString(orgTypeAddDto));
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            //String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String userName = httpServletRequest.getHeader(Constants.NAME);
            companyCode = "000001";
            //userCode = "001001";
            userName = "wjy";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>OrgTypeController method=>addOrgType 新增组织类型，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            /*if (StringUtils.isEmpty(userCode)) {
                log.warn("Route=>OrgTypeController method=>addOrgType 新增组织类型，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }*/
            if (StringUtils.isEmpty(userName)) {
                log.warn("Route=>OrgTypeController method=>addOrgType 新增组织类型，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            if (StringUtils.isEmpty(orgTypeAddDto.getOrgTypeName())) {
                log.warn("新增组织类型失败，参数非法{}", Json.toJsonString(orgTypeAddDto));
                return Result.failWithMsg("组织类型名称为空,添加失败");
            } else {
                //校验组织类型名称是否唯一
                int count = orgTypeService.checkTypeName(orgTypeAddDto.getOrgTypeName(),companyCode);
                if (count > 0) {
                    log.warn("新增组织类型失败，参数非法{}", Json.toJsonString(orgTypeAddDto));
                    return Result.failWithMsg("组织类型不唯一,添加失败");
                }
            }
            if (orgTypeAddDto.getSyncFlag() == null) {
                log.warn("新增组织类型失败，参数非法{}", Json.toJsonString(orgTypeAddDto));
                return Result.failWithMsg("组织类型是否自建标识为空,添加失败");
            } else if (orgTypeAddDto.getSyncFlag() == 0) {
                //校验输入的同步组织类型编码是否唯一
                int count = orgTypeService.checkTypeCode(orgTypeAddDto.getOrgTypeCode(),companyCode);
                if (count > 0) {
                    log.warn("新增组织类型失败，参数非法{}", Json.toJsonString(orgTypeAddDto));
                    return Result.failWithMsg("同步组织类型编码不唯一,添加失败");
                }
            }
            orgTypeAddDto.setCompanyCode(companyCode);
            orgTypeAddDto.setCreatePerson(userName);
            orgTypeService.addOrgType(orgTypeAddDto);
            return Result.success("添加成功");
        } catch (Exception e) {
            LOGGER.error("Route==>OrgTypeController method=>addOrgType 新增组织类型异常，入参：{}，异常：{}", Json.toJsonString(orgTypeAddDto), e);
            return handleException(e);
        }
    }

    /**
     * 刪除组织类型校验
     * @param orgTypeAddDto
     * @return
     */
    @PostMapping("/deleteOrgTypeCheck")
    public Result deleteOrgTypeCheck(HttpServletRequest httpServletRequest, @RequestBody OrgTypeAddDto orgTypeAddDto) {
        log.info("Route=>OrgTypeController method=>deleteOrgTypeCheck 刪除组织类型校验：{}", Json.toJsonString(orgTypeAddDto));
        try {
            // todo  wjy  临时获取companyCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            companyCode = "000001";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>OrgTypeController method=>deleteOrgTypeCheck 刪除组织类型校验，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            String orgTypeCode = orgTypeAddDto.getOrgTypeCode();
            if (StringUtils.isEmpty(orgTypeCode)) {
                log.info("刪除组织类型失败,参数非法{}", orgTypeCode);
                //return new Result(Result.FAIL, "组织类型编码为空");
                return Result.failWithMsg("组织类型编码为空,校验删除组织类型失败");
            }
            //根据组织类型获取组织类型下组织数量
            int orgCount = orgTypeService.selectOrgCount(orgTypeCode, companyCode);
            if (orgCount > 0) {
                //根据组织类型获取用户数量
                int userCount = orgTypeService.selectOrgUserCount(orgTypeCode, companyCode);
                if (userCount > 0) {
                    return Result.success("该组织类型下绑定对应用户,不能进行删除", "11");
                } else {
                    return Result.success("该组织类型下绑定对应组织,可以进行删除", "01");
                }
            }else {
                return Result.success("该组织下没有组织结构且没有关联的用户,可以进行删除", "00");
            }
        } catch (Exception e) {
            LOGGER.error("Route==>OrgTypeController method=>deleteOrgTypeCheck 刪除组织类型校验异常，入参：{}，异常：{}", Json.toJsonString(orgTypeAddDto), e);
            return handleException(e);
        }
    }


    /**
     * 逻辑删除组织类型
     *
     * @param deleteDto
     * @return
     */
    @PostMapping("/deleteOrgType")
    //@LogDb
    public Result deleteOrgType(HttpServletRequest httpServletRequest, @RequestBody OrgTypeDeleteDto deleteDto) {
        log.info("Route=>OrgTypeController method=>deleteOrgType 逻辑删除组织类型：{}", Json.toJsonString(deleteDto));
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            //String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String userName = httpServletRequest.getHeader(Constants.NAME);
            companyCode = "000001";
            //userCode = "001001";
            userName = "wjy";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>OrgTypeController method=>deleteOrgType 逻辑删除组织类型，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            /*if (StringUtils.isEmpty(userCode)) {
                log.warn("Route=>OrgTypeController method=>deleteOrgType 逻辑删除组织类型，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }*/
            if (StringUtils.isEmpty(userName)) {
                log.warn("Route=>OrgTypeController method=>deleteOrgType 逻辑删除组织类型，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            deleteDto.setCompanyCode(companyCode);
            deleteDto.setUpdatePerson(userName);

            if (StringUtils.isEmpty(deleteDto.getOrgTypeCode())) {
                return new Result(Result.FAIL, "没有组织类型编码,无法删除");
            }
            //根据组织类型编码逻辑删除组织类型
            orgTypeService.deleteOrgType(deleteDto);
            return new Result<>(Result.SUCCESS, "删除成功");
        } catch (Exception e) {
            LOGGER.error("Route==>OrgTypeController method=>deleteOrgType 逻辑删除组织类型异常，入参：{}，异常：{}", Json.toJsonString(deleteDto), e);
            return handleException(e);
        }
    }


    /**
     * 新增组织类型字段数据
     * @param httpServletRequest
     * @param orgTypeFieldAddDto
     * @return
     */
    @PostMapping("/addOrgTypeField")
    //@LogDb
    public Result addOrgTypeField(HttpServletRequest httpServletRequest, @RequestBody OrgTypeFieldAddDto orgTypeFieldAddDto) {
        log.info("Route=>OrgTypeController method=>addOrgTypeField 新增组织类型字段数据：{}", Json.toJsonString(orgTypeFieldAddDto));
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            //String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String userName = httpServletRequest.getHeader(Constants.NAME);
            companyCode = "000001";
            //userCode = "001001";
            userName = "wjy";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>OrgTypeController method=>addOrgTypeField 新增组织类型字段数据，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            /*if (StringUtils.isEmpty(userCode)) {
                log.warn("Route=>OrgTypeController method=>addOrgTypeField 新增组织类型字段数据，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }*/
            if (StringUtils.isEmpty(userName)) {
                log.warn("Route=>OrgTypeController method=>addOrgTypeField 新增组织类型字段数据，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            orgTypeFieldAddDto.setCompanyCode(companyCode);
            orgTypeFieldAddDto.setCreatePerson(userName);

            if (StringUtils.isEmpty(orgTypeFieldAddDto.getOrgTypeCode())) {
                return new Result(Result.FAIL, "没有组织类型编码,无法添加");
            }
            if (StringUtils.isEmpty(orgTypeFieldAddDto.getFieldName())) {
                return new Result(Result.FAIL, "没有字段名称,无法添加");
            }
            if (StringUtils.isEmpty(orgTypeFieldAddDto.getFieldInfo())) {
                return new Result(Result.FAIL, "没有字段描述,无法添加");
            }
            //新增组织类型字段
            orgTypeService.addOrgTypeField(orgTypeFieldAddDto);
            return new Result(Result.SUCCESS, "新增成功");
        } catch (Exception e) {
            LOGGER.error("Route==>OrgTypeController method=>addOrgTypeField 新增组织类型字段数据异常，入参：{}，异常：{}", Json.toJsonString(orgTypeFieldAddDto), e);
            return handleException(e);
        }
    }


    /**
     * 修改字段
     *
     * @param orgTypeFieldUpdateDto
     * @return
     */
    @PostMapping("/updateOrgTypeField")
    //@LogDb
    public Result updateOrgTypeField(HttpServletRequest httpServletRequest, @RequestBody OrgTypeFieldUpdateDto orgTypeFieldUpdateDto) {
        log.info("Route=>OrgTypeController method=>updateOrgTypeField 修改字段：{}", Json.toJsonString(orgTypeFieldUpdateDto));
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            //String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String userName = httpServletRequest.getHeader(Constants.NAME);
            companyCode = "000001";
            //userCode = "001001";
            userName = "wjy";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>OrgTypeController method=>updateOrgTypeField 修改字段，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            /*if (StringUtils.isEmpty(userCode)) {
                log.warn("Route=>OrgTypeController method=>updateOrgTypeField 修改字段，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }*/
            if (StringUtils.isEmpty(userName)) {
                log.warn("Route=>OrgTypeController method=>updateOrgTypeField 修改字段，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            orgTypeFieldUpdateDto.setCompanyCode(companyCode);
            orgTypeFieldUpdateDto.setUpdatePerson(userName);

            if (StringUtils.isEmpty(orgTypeFieldUpdateDto.getFieldId())) {
                return new Result(Result.FAIL, "没有字段id,无法修改");
            }
            //修改字段
            orgTypeService.updateOrgTypeField(orgTypeFieldUpdateDto);
            return new Result(Result.SUCCESS, "修改成功");
        } catch (Exception e) {
            LOGGER.error("Route==>OrgTypeController method=>updateOrgTypeField 修改字段异常，入参：{}，异常：{}", Json.toJsonString(orgTypeFieldUpdateDto), e);
            return handleException(e);
        }
    }

    /**
     * 删除组织类型字段(批量)
     * @param orgTypeFieldUpdateDto
     * @return
     */
    @PostMapping("/deleteOrgTypeField")
    //@LogDb
    public Result deleteOrgTypeField(HttpServletRequest httpServletRequest, @RequestBody OrgTypeFieldUpdateDto orgTypeFieldUpdateDto) {
        log.info("Route=>OrgTypeController method=>deleteOrgTypeField 删除组织类型字段(批量)：{}", Json.toJsonString(orgTypeFieldUpdateDto));
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            //String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String userName = httpServletRequest.getHeader(Constants.NAME);
            companyCode = "000001";
            //userCode = "001001";
            userName = "wjy";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>OrgTypeController method=>deleteOrgTypeField 删除组织类型字段，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            /*if (StringUtils.isEmpty(userCode)) {
                log.warn("Route=>OrgTypeController method=>deleteOrgTypeField 删除组织类型字段，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }*/
            if (StringUtils.isEmpty(userName)) {
                log.warn("Route=>OrgTypeController method=>deleteOrgTypeField 删除组织类型字段，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            orgTypeFieldUpdateDto.setCompanyCode(companyCode);
            orgTypeFieldUpdateDto.setUpdatePerson(userName);

            if (CollectionUtils.isEmpty(orgTypeFieldUpdateDto.getFieldIds())) {
                return new Result(Result.FAIL, "请选择数据再进行删除！");
            }
            //删除组织类型字段(批量)
            orgTypeService.deleteOrgTypeField(orgTypeFieldUpdateDto);
            return new Result(Result.SUCCESS, "删除成功");
        } catch (Exception e) {
            LOGGER.error("Route==>OrgTypeController method=>deleteOrgTypeField 删除组织类型字段(批量)异常，入参：{}，异常：{}", Json.toJsonString(orgTypeFieldUpdateDto), e);
            return handleException(e);
        }
    }

    /**
     * 查询对应组织类型下所有字段(分页)
     *
     * @param orgTypeFieldSelectDto
     * @return
     */
    @PostMapping("/selectOrgTypeFieldList")
    public Result selectOrgTypeFieldList(HttpServletRequest httpServletRequest, @RequestBody OrgTypeFieldSelectDto orgTypeFieldSelectDto) {
        log.info("Route=>OrgTypeController method=>selectOrgTypeFieldList 查询对应组织类型下所有字段(分页)：{}", Json.toJsonString(orgTypeFieldSelectDto));
        try {
            // todo  wjy  临时获取companyCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            companyCode = "000001";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>OrgTypeController method=>selectOrgTypeFieldList 查询对应组织类型下所有字段，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            orgTypeFieldSelectDto.setCompanyCode(companyCode);

            if (StringUtils.isEmpty(orgTypeFieldSelectDto.getOrgTypeCode())) {
                return new Result(Result.FAIL, "没有组织类型编码,查询出错");
            }
            //查询对应组织类型下所有字段(分页)
            PageInfo list = orgTypeService.selectOrgTypeFieldList(orgTypeFieldSelectDto);
            return new Result(Result.SUCCESS, "查询成功", list);
        } catch (Exception e) {
            LOGGER.error("Route==>OrgTypeController method=>selectOrgTypeFieldList 查询对应组织类型下所有字段(分页)异常，入参：{}，异常：{}", Json.toJsonString(orgTypeFieldSelectDto), e);
            return handleException(e);
        }
    }

    /**
     * 复制字段
     * @param orgTypeFieldUpdateDto
     * @return
     */
    @PostMapping("/copyOrgTypeField")
    //@LogDb
    public Result copyOrgTypeField(HttpServletRequest httpServletRequest, @RequestBody OrgTypeFieldUpdateDto orgTypeFieldUpdateDto) {
        log.info("Route=>OrgTypeController method=>copyOrgTypeField 复制字段：{}", Json.toJsonString(orgTypeFieldUpdateDto));
        try {
            // todo  wjy  临时获取companyCode和userCode方法
            String companyCode = httpServletRequest.getHeader(Constants.COMPANY_CODE);
            //String userCode = httpServletRequest.getHeader(Constants.USER_CODE);
            String userName = httpServletRequest.getHeader(Constants.NAME);
            companyCode = "000001";
            //userCode = "001001";
            userName = "wjy";
            if (StringUtils.isEmpty(companyCode)) {
                log.warn("Route=>OrgTypeController method=>copyOrgTypeField 复制字段，当前登录人归属租户信息异常");
                return Result.failWithMsg("登录人归属租户信息异常");
            }
            /*if (StringUtils.isEmpty(userCode)) {
                log.warn("Route=>OrgTypeController method=>copyOrgTypeField 复制字段，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }*/
            if (StringUtils.isEmpty(userName)) {
                log.warn("Route=>OrgTypeController method=>copyOrgTypeField 复制字段，当前登录人信息异常");
                return Result.failWithMsg("登录人信息异常");
            }
            orgTypeFieldUpdateDto.setCompanyCode(companyCode);
            orgTypeFieldUpdateDto.setUpdatePerson(userName);

            if (StringUtils.isEmpty(orgTypeFieldUpdateDto.getOrgTypeCode())) {
                return new Result(Result.FAIL, "没有组织类型编码,无法复制");
            }
            if (CollectionUtils.isEmpty(orgTypeFieldUpdateDto.getFieldIds())) {
                return new Result(Result.FAIL, "未选择数据,无法复制");
            }
            //复制字段
            orgTypeService.copyOrgTypeField(orgTypeFieldUpdateDto);
            return new Result(Result.SUCCESS, "复制成功");
        } catch (Exception e) {
            LOGGER.error("Route==>OrgTypeController method=>copyOrgTypeField 复制字段异常，入参：{}，异常：{}", Json.toJsonString(orgTypeFieldUpdateDto), e);
            return handleException(e);
        }
    }

}
